package com.cib.ajax.rpc.util;

import java.lang.reflect.Method;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSON2JavaMethodUtil {

	
	
	/**
	 * 暂时不支持同一个类中同名的method
	 * @param methodName
	 * @param serviceInterface
	 * @return
	 */
	public Method findOperation(String methodName , Class<?> serviceInterface )
	{
		Method[] operations = serviceInterface.getMethods();

		Method result = null;
		for (int i = 0; i < operations.length; i++) {
			Method method2 = operations[i];
			if (method2.getName().equals(methodName)) {
				result = method2;
				break;
			}
		}
		return result;		
	}
	
	/**
	 * 
	 * @param jsonReq 从js传来的json object	
	 * @param serviceInterface 目标方法所在的接口
	 * @return
	 */
	public Object[] transferToJavaParameters(JSONObject jsonReq , Class<?> serviceInterface)
	{
		Object[] args = null;		
		// Extract the arguments		
		try {
			JSONArray array = jsonReq.getJSONArray("params");
			
			args = new Object[array.length()];
			for (int i = 0; i < args.length; i++) {
				Object temp = array.get(i);								
				
				if (temp instanceof JSONObject) {
					String javaClazz = ((JSONObject) temp).optString(
							"javaClass", null);

					if (null != javaClazz) {
						JSON2JavaBean transform = new JSON2JavaBean();
						args[i] = transform.transform(temp, Class
								.forName(javaClazz));
					} else {
						args[i] = temp;
					}
				} else {
					args[i] = array.get(i);
				}
			}	
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
		return args;
	}
}
